<?php
set_time_limit(0);

class KokoTask extends sfBaseTask
{
  protected function configure()
  {
    
	$this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name', 'frontend'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'propel'),
    ));

    $this->namespace        = 'master';
    $this->name             = 'run';
    $this->briefDescription = '';
    $this->detailedDescription = '';
  }

  
  
  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $con=sfProjectConfiguration::getApplicationConfiguration('frontend', 'dev', true);
    $context=sfContext::createInstance($con);
    $con->loadHelpers('Partial');
   
    $routing = $context->getRouting();
    
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'] ? $options['connection'] : null)->getConnection();
	
	$ogMaster=new gameMaster($this);
	
        $ogMaster->AddLog('Szukam tuniejow',$this->name,0);
        
                
	$aTournamentList=TournamentPeer::getPlaying();
		
	foreach($aTournamentList as $oTournament)
	{
	  
          $ogMaster->AddLog('Sprawdzam tournament: '.$oTournament->getId(),$this->name,0);
          
          if($ogMaster->IsNeedRandomize($oTournament))
          {
             if($oTournament->getAckRound()<$oTournament->getRound())
             {
                $ack_round=$oTournament->getAckRound()+1;
                switch($oTournament->getType())
		{
			case Tournament::$GAME_TYPE_ALL:
                        {
                            $iCountPlayers=$ogMaster->playerShereAll($oTournament,$ack_round);
                            
                            if($ack_round==1)
                            {
                                $oTournament->setRound((($iCountPlayers%2)?$iCountPlayers:$iCountPlayers-1)*$oTournament->getRound());
                            }//UPDATE `game`.`game_match` SET `status` = '1'
                            
                            $ogMaster->AddLog('init: all',$this->name,0);
                        }
                        break;
			case Tournament::$GAME_TYPE_RANDOM:
				$ogMaster->playerShereRandom($oTournament,$ack_round);
                                $ogMaster->AddLog('init: random',$this->name,0);
                        break;
			case Tournament::$GAME_TYPE_SWISS:
                        {
                            $ogMaster->playerShereSwiss($oTournament,$ack_round);
                            $ogMaster->AddLog('init: swiss',$this->name,0);
                        }
			break;
                }
                $ogMaster->AddLog('init: startujemy runde '.$ack_round.'/'.$oTournament->getRound(),$this->name,0);
                $oTournament->setAckRound($ack_round);
             }else{ 
                $ogMaster->AddLog('init: koncze turniej',$this->name,0);
                
                $aPlayers=ActivPlayerPeer::retrieveByTournament($oTournament->getId());
                
                $aPlayers_id=array();
                
                foreach ($aPlayers as $player)
                {
                    $aPlayers_id[]=$player->getId();
                }
                
                $c=new Criteria();
                $c->add(ActivPlayerPeer::ID,$aPlayers_id,  Criteria::IN);              
                $c->add(ActivPlayerPeer::STATUS,  ActivPlayer::$ACTION_END_TURNAMENT);             
                $ogMaster->AddLog('ActivPlayerPeer::doUpdate: '.ActivPlayerPeer::doUpdate($c),$this->name,0);
              
                $oTournament->setStatus(Tournament::$GAME_STATUS_ENDED);
             }
                
             $oTournament->save();
             
          }else{
              $gReferee=new gameReferee($this);
              
              $gReferee->AddLog('init: gramy',$this->name,0);
                          
                                        
              $match_id=$gReferee->changeStatusToEnd($oTournament);
                            
             
              $c=new Criteria();
              $c->add(GameMatchPeer::ID,$match_id,  Criteria::IN);
              $c->add(GameMatchPeer::TOURNAMENT_ID,$oTournament->getId());
              //$c->add(GameMatchPeer::STATUS,GameMatch::$GAMEMATCH_STATUS_START);
              $matches=GameMatchPeer::doSelect($c);
              
              $rules = unserialize($oTournament->getRules()->getData());
              
              $ended_match=array();
              $ended_result=null;
              
              switch($rules->getMatchEndType())
              {
                  case gameRules::$EM_GAME:
                      $ended_match=$gReferee->EndGame($matches,$match_id,$rules->getMatchEndValue()); 
                      $ended_result=$gReferee->EndGameResult($ended_match,$rules->getWinPoints());
                  break;
                  case gameRules::$EM_POINTS:
                      $ended_match=$gReferee->EndPoints($matches,$match_id,$rules->getMatchEndValue(),$rules->getWinPoints()); 
                      $ended_result=$gReferee->EndGameResult($ended_match,$rules->getWinPoints());
                  break;
                  case gameRules::$EM_POINTS_DIF:
                      $ended_match=$gReferee->EndDiffPoints($matches,$match_id,$rules->getMatchEndValue()); 
                      $ended_result=$gReferee->EndGameResult($ended_match,$rules->getWinPoints());
                  break;
                  case gameRules::$EM_WINS:
                      $ended_match=$gReferee->EndWins($matches,$match_id,$rules->getMatchEndValue(),gameRules::$GW_Less);
                      $ended_result=$gReferee->EndWinsResult($matches, gameRules::$GW_Less);
                  break;
              }
              
              
              
              $gReferee->AddLog('getMatchEndType'.var_dump($ended_match),$this->name,0);
              $gReferee->AddLog('$ended_result'.var_dump($ended_result),$this->name,0);
                            
              $c=new Criteria();
              $c->add(GameMatchPeer::ID,$ended_result[0],  Criteria::IN);              
              $c->add(GameMatchPeer::RESULT,  GameMatch::$GAMEMATCH_RESULT_DRAW);             
              $this->logSection($this->name, 'GameMatchPeer::doUpdate: '.GameMatchPeer::doUpdate($c),$this->name,0);
              
              
              $c=new Criteria();
              $c->add(GameMatchPeer::ID,$ended_result[1],  Criteria::IN);              
              $c->add(GameMatchPeer::RESULT,  GameMatch::$GAMEMATCH_RESULT_FIRST);             
              $gReferee->AddLog('GameMatchPeer::doUpdate: '.GameMatchPeer::doUpdate($c),$this->name,0);
              
              $c=new Criteria();
              $c->add(GameMatchPeer::ID,$ended_result[2],  Criteria::IN);              
              $c->add(GameMatchPeer::RESULT,  GameMatch::$GAMEMATCH_RESULT_SECOND);             
              $gReferee->AddLog('GameMatchPeer::doUpdate: '.GameMatchPeer::doUpdate($c),$this->name,0);
              
              
              $c=new Criteria();
              $c->add(GameMatchPeer::ID,$ended_match,  Criteria::IN);              
              $c->add(GameMatchPeer::STATUS,  GameMatch::$GAMEMATCH_STATUS_ENDED); 
              
              $gReferee->AddLog('GameMatchPeer::doUpdate: '.GameMatchPeer::doUpdate($c),$this->name,0);
              
              $end_players=array();
              
              foreach ($matches as $match)
              {
                  if(in_array($match->getId(),$ended_match))
                  {
                      $end_players[]=$match->getFirstPlayerId();
                      $end_players[]=$match->getSecondPlayerId();
                  }
              }
              
              $gReferee->AddLog('$end_players: '.$end_players,$this->name,0);
                            
              $c=new Criteria();
              $c->add(ActivPlayerPeer::ID,$end_players,  Criteria::IN);              
              $c->add(ActivPlayerPeer::STATUS,  ActivPlayer::$ACTION_FREE);              
              $gReferee->AddLog('ActivPlayerPeer::doUpdate: '.ActivPlayerPeer::doUpdate($c),$this->name,0);    
              
              
              //Tworzymy nowe gry
              $c = new Criteria();
              $c->addSelectColumn(GamePeer::MATCH_ID);
             // $c->addSelectColumn(GamePeer::SWITCHES);
              $c->addSelectColumn('MAX('.GamePeer::CREATED_AT.') as cnt');
              $c->addSelectColumn(GamePeer::CREATED_AT);
              $c->add(GamePeer::MATCH_ID,array_diff($match_id,$ended_match),Criteria::IN);
              $c->addGroupByColumn(GamePeer::MATCH_ID);
              $res=GamePeer::doSelectStmt($c); 
              
              $gReferee->AddLog('$end_players: '.  var_dump($res),$this->name,0);
              
              
              foreach ($res->fetchAll() as $node)
              {
                  //$result[]=array($node[0],$node[1]);
                  
                    $gm=new Game();
                    $gm->setMatchId($node[0]);
                    $gm->setStatus(Game::$GAME_STATUS_START);
                    //$gm->setSwitches(!$node[1]);
                    if($rules->getType()==gameRules::$RT_TREE)
                    {
                        $gm->setNode($ogMaster->getGameNode($rules));
                    }
                    $gm->save();
              }                 
          }
          
	}	
       
        $ogMaster->AddLog('Koniec',$this->name,0);
     
  }
}